import { getCategory } from '@/services/chdstore';
import { Image, Select, Space, Spin } from 'antd';
import { debounce } from 'lodash-es';
import { useMemo, useRef, useState } from 'react';

const SearchSelect = (props) => {
  const { dataSource, setDataSource, recordKey } = props;

  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState<any[]>([]);
  const fetchRef = useRef(0);

  const loadOptions = (value: any) => {
    fetchRef.current += 1;
    const fetchId = fetchRef.current;
    setOptions([]);
    setFetching(true);

    getCategory(value).then((res) => {
      if (fetchId !== fetchRef.current) {
        // for fetch callback order
        return;
      }

      setOptions(
        res.data.map((item) => {
          return {
            extra: item,
            value: item.code,
            disabled: !!dataSource.find((items) => items.code === item.code),
            label: (
              <Space>
                <Image src={item.pic} width={28} />
                <div>{item.goodsName}</div>
                <div>（{item.price}）</div>
              </Space>
            ),
          };
        }),
      );
      setFetching(false);
    });
  };

  const debounceFetcher = useMemo(() => {
    return debounce(loadOptions, 800);
  }, [getCategory]);

  const onChange = (val) => {
    const obj = options.find((item) => item.value === val);
    const newDataSource = dataSource.map((item) => {
      if (item.id === recordKey) {
        return {
          id: recordKey,
          ...obj?.extra,
        };
      }
      return item;
    });
    setDataSource(newDataSource);

    props.onChange(val);
  };

  return (
    <div>
      <Select
        placeholder="请输入道具名称"
        allowClear
        showSearch
        filterOption={false}
        onSearch={debounceFetcher}
        notFoundContent={fetching ? <Spin size="small" /> : null}
        value={props.value}
        onFocus={(e) => loadOptions(e.target.value)}
        onChange={onChange}
        options={options}
      />
    </div>
  );
};

export default SearchSelect;
